package com.hui.qiniucloud.controller;

import com.hui.qiniucloud.dto.*;
import com.hui.qiniucloud.entity.AppHttpCodeEnum;
import com.hui.qiniucloud.entity.Result;
import com.hui.qiniucloud.entity.User;
import com.hui.qiniucloud.service.IUserService;
import com.hui.qiniucloud.utils.AppThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;

/**
 * <p>
 * 用户管理控制器
 * </p>
 *
 * @author huihui
 * @since 2025-09-28
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
@Tag(name = "用户管理", description = "用户注册、登录、信息管理等接口")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 用户注册
     */
    @Operation(summary = "用户注册", description = "新用户注册接口")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "注册成功"),
        @ApiResponse(responseCode = "400", description = "参数错误或用户已存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PostMapping("/register")
    public Result<UserResponse> register(@Valid @RequestBody UserRegisterRequest request) {
        try {
            UserResponse userResponse = userService.register(request);
            return Result.success(userResponse);
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "用户登录接口")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "登录成功"),
        @ApiResponse(responseCode = "400", description = "账号或密码错误"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PostMapping("/login")
    public Result<UserLoginResponse> login(@Valid @RequestBody UserLoginRequest request,
                                         HttpServletRequest httpRequest) {
        try {
            String clientIp = getClientIp(httpRequest);
            UserLoginResponse loginResponse = userService.login(request, clientIp);
            return Result.success(loginResponse);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @Operation(summary = "获取用户信息", description = "根据用户ID获取用户详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping
    public Result<UserResponse> getUserInfo() {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            UserResponse userResponse = userService.getUserInfo(user.getId());
            return Result.success(userResponse);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @Operation(summary = "更新用户信息", description = "更新用户基本信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "参数错误"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PutMapping("/update")
    public Result<UserResponse> updateUserInfo(@Valid @RequestBody UserUpdateRequest request) {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long userId = user.getId();
        try {
            UserResponse userResponse = userService.updateUserInfo(userId, request);
            return Result.success(userResponse);
        } catch (Exception e) {
            log.error("更新用户信息失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @Operation(summary = "修改密码", description = "用户修改密码接口")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "密码修改成功"),
        @ApiResponse(responseCode = "400", description = "参数错误或当前密码不正确"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PutMapping("/password")
    public Result<String> updatePassword(
                                       @Valid @RequestBody UserPasswordUpdateRequest request) {
        //获取当前用户id
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Long userId = user.getId();
        try {
            userService.updatePassword(userId, request);
            return Result.success("密码修改成功");
        } catch (Exception e) {
            log.error("修改密码失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 搜索用户
     */
    @Operation(summary = "搜索用户", description = "根据关键词搜索用户（用户名、昵称、邮箱）")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "搜索成功"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/search")
    public Result<List<UserResponse>> searchUsers(@Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        try {
            List<UserResponse> users = userService.searchUsers(keyword);
            return Result.success(users);
        } catch (Exception e) {
            log.error("搜索用户失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取所有用户
     */
    @Operation(summary = "获取所有用户", description = "获取系统中所有活跃用户列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/all")
    public Result<List<UserResponse>> getAllUsers() {
        try {
            List<UserResponse> users = userService.getAllUsers();
            return Result.success(users);
        } catch (Exception e) {
            log.error("获取所有用户失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 更新用户状态
     */
    @Operation(summary = "更新用户状态", description = "启用或禁用用户账号")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "状态更新成功"),
        @ApiResponse(responseCode = "400", description = "参数错误"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PutMapping("/{userId}/status")
    public Result<String> updateUserStatus(@Parameter(description = "用户ID") @PathVariable Long userId,
                                         @Parameter(description = "用户状态：0-禁用，1-启用") @RequestParam Integer status) {
        try {
            if (status != 0 && status != 1) {
                return Result.fail("状态参数错误，只能是0（禁用）或1（启用）");
            }
            userService.updateUserStatus(userId, status);
            return Result.success(status == 1 ? "用户已启用" : "用户已禁用");
        } catch (Exception e) {
            log.error("更新用户状态失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 检查用户名是否可用
     */
    @Operation(summary = "检查用户名", description = "检查用户名是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/check/username")
    public Result<Boolean> checkUsername(@Parameter(description = "用户名") @RequestParam String username) {
        try {
            boolean exists = userService.isUsernameExists(username);
            return Result.success(!exists); // 返回true表示可用，false表示已被使用
        } catch (Exception e) {
            log.error("检查用户名失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 检查邮箱是否可用
     */
    @Operation(summary = "检查邮箱", description = "检查邮箱是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/check/email")
    public Result<Boolean> checkEmail(@Parameter(description = "邮箱") @RequestParam String email) {
        try {
            boolean exists = userService.isEmailExists(email);
            return Result.success(!exists); // 返回true表示可用，false表示已被使用
        } catch (Exception e) {
            log.error("检查邮箱失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 检查手机号是否可用
     */
    @Operation(summary = "检查手机号", description = "检查手机号是否已被使用")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "检查完成"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/check/phone")
    public Result<Boolean> checkPhone(@Parameter(description = "手机号") @RequestParam String phone) {
        try {
            boolean exists = userService.isPhoneExists(phone);
            return Result.success(!exists); // 返回true表示可用，false表示已被使用
        } catch (Exception e) {
            log.error("检查手机号失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多个IP的情况，取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        return ip;
    }
}
